<template>
	<view class="page col-3e bg-fff">
        <!-- #ifdef MP-WEIXIN -->
        <block v-if="versionValid">
            <button class="avatarBtn clearBtn flex" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                <up-avatar :src="avatarUrl" shape="square"></up-avatar>
            </button>
            <view class="inpwrap flex">
                <text class="label left-15">昵称</text>
                <input type="nickname" v-model="nickname" class="inp" placeholder="请输入昵称" @change="getNickname" />
            </view>
        </block>
        <block v-else>
            <button class="avatarBtn clearBtn flex" @click="uploadImgBtn">
                <up-avatar :src="avatarUrl" shape="square"></up-avatar>
            </button>
            <view class="inpwrap flex">
                <text class="label left-15">昵称</text>
                <input v-model="nickname" class="inp" placeholder="请输入昵称"/>
            </view>
        </block>
        <!-- #endif -->

        <!-- #ifdef MP-BAIDU || MP-TOUTIAO -->
        <button class="avatarBtn clearBtn flex" @click="uploadImgBtn">
            <up-avatar :src="avatarUrl" shape="square"></up-avatar>
        </button>
        <view class="inpwrap flex">
            <text class="label left-15">昵称</text>
            <input v-model="nickname" class="inp" placeholder="请输入昵称"/>
        </view>
        <!-- #endif -->
        
        <button class="submitBtn clearBtn" @click="submitClick">提交</button>

        <up-modal :show="showPrivacy" title="用户隐私保护提示" :showCloseBtn="false" :showConfirmButton="false" @close="showPrivacy = false" @confirm="showPrivacy = false">
            <privacy-authorize class="width-100" @close="closePrivacyModal"></privacy-authorize>
        </up-modal>
	</view>
</template>

<script>
import { mapState, mapActions } from 'pinia';
import { useUserInfoStore, useIndexStore, useConfigStore } from '@/store/index';
import { checkWXPrivacyAuthorize, checkUploadImageParam, versionFunegt, uuid, getFileType } from '@/common/common';
import { upload_image } from '@/common/common';
import { submitUserInfo } from '@/common/api/user';
export default {
	data() {
		return {
            avatarFilePath: '',
            avatarUrl: '',
            nickname: '',
            versionValid: false,
            showPrivacy: false
		}
	},
    computed:{
        ...mapState(useUserInfoStore, ['userInfo']),
        ...mapState(useIndexStore, ['uploadParam']),
        ...mapState(useConfigStore, ['WXSDKVersion']),
    },
    onLoad(options) {
        const that = this;
        let { image, nickname, login } = this.userInfo;
        if(login) {
            this.avatarUrl = image;
            this.avatarFilePath = image;
            this.nickname = nickname;
        }
        
        this.versionValid = versionFunegt(this.WXSDKVersion, '2.21.2');
        uni.$check_and_login(function() {
            that.init()
        })
    },
    onShareAppMessage(res) {
        return {
            title: `选楼盘，开盘日历，查限购，查积分，一手掌握`,
            path: '/pages/tabBar/home/index',
        }
    },
	methods: {
        ...mapActions(useUserInfoStore, ['setUserInfo', 'checkUserInfo']),
        
        //初始化获取上传图片参数
        async init(){
            try {
                await this.checkUserInfo();
                await checkUploadImageParam('public');
            } catch (error) {}
            //#ifdef MP-WEIXIN
            checkWXPrivacyAuthorize().then(privacyRes => {
                if(privacyRes) {
                    this.showPrivacy = true;
                }
            })
            //#endif
        },

        //关闭隐私政策模态框
        closePrivacyModal(type) {
            this.showPrivacy = false;
            if(type==='fail') {
                this.versionValid = false;
            }
        },
        
        //低版本兼容上传图片
        uploadImgBtn(){
        	const that = this;
            uni.chooseMedia({
        		count: 1,
                mediaType: ['image'],
        		success: (res) => {
        			let fileObj = {};
        			res.tempFiles.forEach(item => {
        				let name = `avatar/${that.userInfo.id}/${uuid()}${getFileType(item.tempFilePath)}`;
                        fileObj = {url: item.tempFilePath, key: name}
        			})
                    upload_image(that.uploadParam['public'], fileObj.url, fileObj.key, function(uploadRes, uploadKey){
                        that.avatarFilePath = fileObj.key;
                        that.avatarUrl = fileObj.url;
                    });
        		}
        	})
        },
        
        //获取头像回调
        onChooseAvatar(e) {
            const that = this;
            this.avatarUrl = e.detail.avatarUrl;
            let filePath = `avatar/${this.userInfo.id}/${uuid()}${getFileType(e.detail.avatarUrl)}`;
            upload_image(this.uploadParam['public'], e.detail.avatarUrl, filePath, function(res, key){
                that.avatarFilePath = filePath;
            });
        },

        //获取昵称回调
        getNickname(e) {
            this.nickname = e.detail.value
        },
        
        //提交用户信息
        async submitClick() {
            if(!this.avatarFilePath) {
                uni.$u.toast("请上传头像")
                return
            }
            if(!this.nickname) {
                uni.$u.toast("请输入昵称")
                return
            }
            uni.showLoading({
                title: '提交中,请稍后',
                mask: true
            })
            try {
                let res = await submitUserInfo({
                    image: this.avatarFilePath,
                    nickname: this.nickname
                });
                if(res.status !== 0){
                    uni.$u.toast(res.detail)
                    return
                }
                this.setUserInfo(res.detail);
                uni.setStorage({
                    key: 'userInfo',
                    data: {...res.detail},
                    success: () => {
                        uni.navigateBack({
                            delta: 1
                        })
                    }
                })
            } catch(err) {
                uni.$u.toast(err);
            } finally {
                uni.hideLoading();
            }
        }
	}
};
</script>

<style lang="scss" scoped>
.page {
    min-height: 100vh;
    overflow: hidden;
    line-height: 1.3;
    .avatarBtn{
        width: 30%;
        margin: 200rpx auto 50rpx auto;
    }
    .inpwrap{
        padding: 20rpx 0;
        border-top: 2rpx solid rgba(0,0,0,.05);
        border-bottom: 2rpx solid rgba(0,0,0,.05);
        justify-content: space-between;
        .label{
            width: 20%;
        }
        .inp{
            width: 80%;
            padding: 10rpx 0;
        }
    }
    .submitBtn{
        background-color: $theme-color;
        color: #FFFFFF;
        font-size: 30rpx;
        margin: 50rpx 30rpx;
        height: 80rpx;
        line-height: 80rpx;
    }
}
</style>